package com.payment.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.payment.common.base.AjaxResult;
import com.payment.common.enums.SignStatus;
import com.payment.common.enums.SystemConfigCode;
import com.payment.common.support.Convert;
import com.payment.common.type.IncreaseStatus;
import com.payment.common.utils.Md5Utils;
import com.payment.common.utils.StringUtils;
import com.payment.common.utils.pay.EncryptUtil;
import com.payment.system.domain.Acq;
import com.payment.system.domain.AcqBind;
import com.payment.system.domain.CardBin;
import com.payment.system.domain.CardType;
import com.payment.system.domain.IssBank;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.MerchantIncreaseLimit;
import com.payment.system.domain.Remind;
import com.payment.system.domain.SystemConfig;
import com.payment.system.mapper.AcqBindMapper;
import com.payment.system.mapper.AcqMapper;
import com.payment.system.mapper.CardBinMapper;
import com.payment.system.mapper.CardTypeMapper;
import com.payment.system.mapper.IssBankMapper;
import com.payment.system.mapper.MerchantIncreaseLimitMapper;
import com.payment.system.mapper.MerchantMapper;
import com.payment.system.mapper.PlanNewMapper;
import com.payment.system.mapper.RemindMapper;
import com.payment.system.mapper.SystemConfigMapper;
import com.payment.system.service.IMerchantIncreaseLimitService;
import com.payment.system.util.GuangGuUtil;
import com.payment.system.vo.CreditCardVo;
import com.payment.system.vo.MyBankAllVO;

/**
 * 商户信用卡 服务层实现
 *
 * @author payment
 * @date 2018-12-31
 */
@Service
public class MerchantIncreaseLimitServiceImpl implements IMerchantIncreaseLimitService {
	private static final Logger log = LoggerFactory.getLogger(MerchantIncreaseLimitServiceImpl.class);
	@Autowired
	private MerchantIncreaseLimitMapper merchantIncreaseLimitMapper;
	@Autowired
	private AcqBindMapper acqBindMapper;
	@Autowired
	private CardBinMapper binMapper;
	@Autowired
	private CardTypeMapper cardTypeMapper;
	@Autowired
	private IssBankMapper issBankMapper;

	@Autowired
	private MerchantMapper merchantMapper;
	@Autowired
	private AcqMapper acqMapper;
	@Autowired
	private PlanNewMapper planNewMapper;
	@Autowired
	private SystemConfigMapper configMapper;
	@Autowired
	private RemindMapper remindMapper;

	/**
	 * 查询商户信用卡信息
	 *
	 * @param iD
	 *            商户信用卡ID
	 * @return 商户信用卡信息
	 */
	@Override
	public MerchantIncreaseLimit selectMerchantIncreaseLimitById(String iD) {
		return merchantIncreaseLimitMapper.selectMerchantIncreaseLimitById(iD);
	}

	/**
	 * 查询商户信用卡列表
	 *
	 * @param merchantIncreaseLimit
	 *            商户信用卡信息
	 * @return 商户信用卡集合
	 */
	@Override
	public List<MerchantIncreaseLimit> selectMerchantIncreaseLimitList(MerchantIncreaseLimit merchantIncreaseLimit) {
		List<MerchantIncreaseLimit> list = merchantIncreaseLimitMapper
				.selectMerchantIncreaseLimitList(merchantIncreaseLimit);
		for (MerchantIncreaseLimit mer : list) {
			// 敏感信息脱敏
			deDensity(mer);
		}
		return list;
	}

	/**
	 * 信用卡绑卡验证码获取
	 *
	 * @param merchantId
	 *            用户ID
	 * @param companyId
	 *            公司ID
	 * @param bankAccountName
	 *            姓名
	 * @param bankAccount
	 *            信用卡号
	 * @param idCardNumber
	 *            身份证号
	 * @param bankPhone
	 *            预留手机号
	 * @param bankName
	 *            银行名称
	 * @param cvn
	 *            安全码cvn
	 * @param expdate
	 *            有效期
	 * @param trxSourceIp
	 *            调用段ip地址
	 * @throws Exception
	 */
	@Override
	public AjaxResult bindCardMsg(String merchantId, String companyId, String bankAccountName, String bankAccount,
			String idCardNumber, String bankPhone, String bankName, String cvn, String expdate, String trxSourceIp) {
		if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(cvn) || StringUtils.isEmpty(expdate)
				|| StringUtils.isEmpty(trxSourceIp) || StringUtils.isEmpty(bankAccountName)
				|| StringUtils.isEmpty(bankAccount) || StringUtils.isEmpty(idCardNumber)
				|| StringUtils.isEmpty(bankPhone) || StringUtils.isEmpty(bankName)) {
			return AjaxResult.error("绑卡信息无效，缺失参数！");
		}

		// 获取上游商户
		Merchant acqmer = merchantMapper.selectMerchantById(merchantId);
		if (acqmer == null) {
			return AjaxResult.error(1, "绑卡信息无效，请联系客服！");
		}

		if (StringUtils.isEmpty(acqmer.getAcqMerchantNo())) {
			return AjaxResult.error(1, "未实名，请实名");
		}

		if (!idCardNumber.equals(acqmer.getIdCardNumber())) {
			return AjaxResult.error(2, "身份证号不相符，请绑定本人信用卡");
		}
		// 查询银行名称
		IssBank issBank = issBankMapper.selectIssBankByName(bankName);
		String bankCode = issBank.getBankCode();
		if (StringUtils.isNotNull(issBank)) {
			bankCode = issBank.getBankCode();
		} else {
			return AjaxResult.error("暂不支持该银行，请联系客服咨询");
		}
		// 根据卡号查询信用卡信息
		List<MerchantIncreaseLimit> increaseLimits = merchantIncreaseLimitMapper
				.selectCreditCardByCardNumber(bankAccount);
		/** 通过公司id是否为空去获取通道信息 */
		Acq acq = new Acq();
		if (StringUtils.isEmpty(companyId)) {
			/*SystemConfig config = configMapper
					.selectSystemConfigByConfigCode(SystemConfigCode.ACQCODE_CONFIG.getCode());
			String acqCode = config.getConfigValue();
			// 公司ID为空
			acq = acqMapper.selectAcqByCode(acqCode);*/
			List<Acq> acqList = acqMapper.selectAcqListByApp(null);
			List<Acq> romveList = new ArrayList<Acq>();
			for (Acq acqs : acqList) {
				if (!StringUtils.isEmpty(acqs.getSupportBankcode())) {
					String[] support = acqs.getSupportBankcode().split(",");
					if (support != null && !ArrayUtils.contains(support, bankCode)) {
						romveList.add(acqs);
					}
				}
				if (!StringUtils.isEmpty(acqs.getNoSupportBankcode())) {
					String[] noSuppor = acqs.getNoSupportBankcode().split(",");
					if (noSuppor != null && ArrayUtils.contains(noSuppor, bankCode)) {
						romveList.add(acqs);
					}
				}
				if (acqs.getBindType().equals(2) || acqs.getBindType().equals(3)){
					romveList.add(acqs);
				}
			}
			acqList.removeAll(romveList);
			if (acqList == null ||acqList.size()==0){
				return AjaxResult.error(3, "该类型银行信用卡暂无通道支持，无法绑定");
			}
			acq = acqList.get(0);
			// 查询通道需要签约的最近一条记录
			companyId = acq.getAcqCode();
			// 该是否存在或是未删除和签约通道
			if (increaseLimits.size() > 0 && increaseLimits.get(0).getSTATUS().equals(IncreaseStatus.B.getCode())) {
				return AjaxResult.error(3, "该卡号已存在，请联系客服核实资料");
			}
		} else {
			// 公司ID不为空 查询该通道ID
			acq = acqMapper.selectAcqByCode(companyId);
		}
		// 签约订单号，需保证唯一
		String orderNo = StringUtils.createNum();
		// 获取上送信息
		MerchantIncreaseLimit mer = bindCardMsgLimit(acqmer.getAcqMerchantNo(), companyId, bankAccountName, bankAccount,
				idCardNumber, bankPhone, cvn, expdate, trxSourceIp);
		mer.setBankCode(bankCode);
		mer.setSeriaNo(orderNo);
		TreeMap<String, Object> map = new TreeMap<>();
		if (acq.getBindType().equals(1)) {
			map.put("companyId", acq.getAcqCode());
			// 签约订单号，需保证唯一
			map.put("orderNo", orderNo);
			// 上游商户ID
			map.put("acqMerchantNo", acqmer.getAcqMerchantNo());
			return AjaxResult.successAndData("签约成功", map);
		}
		Integer bindType = 0;
		if (acq.getBindType().equals(2) || acq.getBindType().equals(3)) {
			bindType = 1;
		}
		try {
			JSONObject gg = GuangGuUtil.bankCardSignSendSms(mer, bindType);
			if (StringUtils.isNotNull(gg)) {
				String retCode = gg.getString("ret_code");
				String resCode = gg.getString("res_code");
				if (("SUCCESS").equals(retCode)) {
					if (("YQB000000").equals(resCode)) {
						// 公司ID
						map.put("companyId", companyId);
						// 签约订单号，需保证唯一
						map.put("orderNo", orderNo);
						// 上游商户ID
						map.put("acqMerchantNo", acqmer.getAcqMerchantNo());
						map.put("url", gg.getString("url"));
						map.put("html", gg.getString("html"));
						return AjaxResult.successAndData("发送成功", map);
					} else if (("YQB010004").equals(resCode)) {
						// 公司ID
						map.put("companyId", companyId);
						// 签约订单号，需保证唯一
						map.put("orderNo", orderNo);
						// 上游商户ID
						map.put("acqMerchantNo", acqmer.getAcqMerchantNo());
						return AjaxResult.successAndData("签约成功", map);
					} else {
						return AjaxResult.error(gg.getString("res_msg"));
					}
				}
			}
		} catch (Exception e) {
			log.error("app验证码发送失败{}", e);
			return AjaxResult.error("验证码发送失败，请联系客服咨询");
		}
		return AjaxResult.error("验证码发送失败，请联系客服咨询");
	}

	/**
	 * app 商户新增信用卡
	 *
	 * @param merchantId
	 *            用户ID
	 * @param acqMerchantNo
	 *            上游商户id
	 * @param companyId
	 *            公司ID
	 * @param bankAccountName
	 *            姓名
	 * @param bankAccount
	 *            信用卡号
	 * @param idCardNumber
	 *            身份证号
	 * @param bankPhone
	 *            预留手机号
	 * @param bankName
	 *            银行名称
	 * @param cvn
	 *            安全码CVN
	 * @param expDate
	 *            有效期
	 * @param trxSourceIp
	 *            调用段ip地址
	 * @param orderNo
	 *            签约订单号，需保证唯一
	 * @param repaymentDay
	 *            还款日
	 * @param billDay
	 *            账单日
	 * @param limitMoney
	 *            额度
	 * @param smsCode
	 *            短信验证码
	 * @param smsType
	 *            是否需要短信验证码 0需要 1不需要
	 */
	@Override
	public AjaxResult insertMerchantIncreaseLimit(String merchantId, String acqMerchantNo, String companyId,
			String bankAccountName, String bankAccount, String idCardNumber, String bankPhone, String bankName,
			String cvn, String expDate, String trxSourceIp, String repaymentDay, String billDay, String limitMoney,
			String orderNo, String smsCode, Integer smsType) {
		if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(acqMerchantNo) || StringUtils.isEmpty(companyId)
				|| StringUtils.isEmpty(bankAccountName) || StringUtils.isEmpty(bankAccount)
				|| StringUtils.isEmpty(idCardNumber) || StringUtils.isEmpty(bankPhone) || StringUtils.isEmpty(bankName)
				|| StringUtils.isEmpty(cvn) || StringUtils.isEmpty(expDate) || StringUtils.isEmpty(trxSourceIp)
				|| StringUtils.isEmpty(repaymentDay) || StringUtils.isEmpty(billDay) || StringUtils.isEmpty(limitMoney)
				|| StringUtils.isEmpty(orderNo)) {
			return AjaxResult.error("添加信用卡失败，缺失参数！");
		}
		if (StringUtils.isEmpty(smsCode)) {
			return AjaxResult.error("添加信用卡失败：验证码不能为空");
		}
		// 查询信用卡
		MerchantIncreaseLimit increaseLimit1 = merchantIncreaseLimitMapper
				.selectCreditCardByCardIdAndMerchantId(bankAccount, merchantId);
		// 查询通道需要签约的最近一条记录
		Acq acq = new Acq();
		// 判断公司ID是否为空
		if (StringUtils.isEmpty(companyId)) {
			SystemConfig config = configMapper
					.selectSystemConfigByConfigCode(SystemConfigCode.ACQCODE_CONFIG.getCode());
			String acqCode = config.getConfigValue();
			// 公司ID为空
			acq = acqMapper.selectAcqByCode(acqCode);
			companyId = acq.getAcqCode();
			if (increaseLimit1 != null && increaseLimit1.getSTATUS().equals(IncreaseStatus.B.getCode())) {
				return AjaxResult.error(3, "您已添加该卡了，请勿重复添加！");
			}
		} else {
			// 公司ID不为空 查询该通道ID
			acq = acqMapper.selectAcqByCode(companyId);
		}
		// 获取上送信息
		MerchantIncreaseLimit mer = merchantIncreaseLimit(acqMerchantNo, companyId, bankAccountName, bankAccount,
				idCardNumber, bankPhone, cvn, expDate, trxSourceIp, smsCode);
		// 查询银行名称
		IssBank issBank = issBankMapper.selectIssBankByName(bankName);
		if (StringUtils.isNotNull(issBank)) {
			// 银行代码
			mer.setBankCode(issBank.getBankCode());
		} else {
			return AjaxResult.error("暂不支持该银行，请联系客服咨询");
		}
		// 请求流水号
		mer.setSeriaNo(orderNo);
		// 添加用户ID
		mer.setMerchantId(merchantId);
		if (smsType.equals(0)) {
			try {
				// 银行卡签约(信用卡)
				JSONObject gg = GuangGuUtil.signingCard(mer);
				if (StringUtils.isNotNull(gg)) {
					String retCode = gg.getString("ret_code");
					String resCode = gg.getString("res_code");
					if (("SUCCESS").equals(retCode) && ("YQB000000").equals(resCode)) {
						if (("1").equals(gg.getString("status"))) {
							// 添加卡信息
							String limitId = StringUtils.randomUUID();
							// 银行名称（银行代码）
							mer.setBankName(issBank.getBankCode());
							// 还款日
							mer.setRepaymentDay(repaymentDay);
							// 账单日
							mer.setBillDay(billDay);
							// 额度
							mer.setLimitMoney(limitMoney);
							// 信用卡审核状态
							mer.setSTATUS(IncreaseStatus.B.getCode());
							// 信用卡提额审核状态
							mer.setIncreaseLimitStatus(IncreaseStatus.B.getCode());
							if (increaseLimit1 != null) {
								mer.setID(increaseLimit1.getID());
								merchantIncreaseLimitMapper.updateMerchantIncreaseLimit(mer);
							} else {
								mer.setID(limitId);
								merchantIncreaseLimitMapper.insertMerchantIncreaseLimit(mer);
							}
							// 添加卡BIN
							Acq acq1 = acqMapper.selectAcqByCode(companyId);
							AcqBind acqBind = new AcqBind();
							acqBind.setId(StringUtils.randomUUID());
							acqBind.setAcqId(acq1.getId());
							acqBind.setCardId(mer.getID());
							acqBindMapper.insertAcqBind(acqBind);
							// APP返回银行名称
							mer.setBankName(bankName);
							SaveUpdateRemind(mer, issBank.getShortCnName());
							return AjaxResult.successAndData("添加信用卡成功", mer);
						} else {
							return AjaxResult.error(gg.getString("res_msg"));
						}
					} else {
						return AjaxResult.error(gg.getString("res_msg"));
					}
				}
			} catch (Exception e) {
				log.error("添加信用卡失败{}", e);
				return AjaxResult.error("添加信用卡失败，请联系客服咨询");
			}
		} else if (smsType.equals(1)) {
			// 添加卡信息
			String limitId = StringUtils.randomUUID();
			// 银行名称（银行代码）
			mer.setBankName(issBank.getBankCode());
			// 还款日
			mer.setRepaymentDay(repaymentDay);
			// 账单日
			mer.setBillDay(billDay);
			// 额度
			mer.setLimitMoney(limitMoney);
			// 信用卡审核状态
			mer.setSTATUS(IncreaseStatus.B.getCode());
			// 信用卡提额审核状态
			mer.setIncreaseLimitStatus(IncreaseStatus.B.getCode());
			if (increaseLimit1 != null) {
				mer.setID(increaseLimit1.getID());
				merchantIncreaseLimitMapper.updateMerchantIncreaseLimit(mer);
			} else {
				mer.setID(limitId);
				merchantIncreaseLimitMapper.insertMerchantIncreaseLimit(mer);
			}
			// 添加卡BIN
			Acq acq1 = acqMapper.selectAcqByCode(companyId);
			AcqBind acqBind = new AcqBind();
			acqBind.setId(StringUtils.randomUUID());
			acqBind.setAcqId(acq1.getId());
			acqBind.setCardId(mer.getID());
			acqBindMapper.insertAcqBind(acqBind);
			// APP返回银行名称
			mer.setBankName(bankName);
			SaveUpdateRemind(mer, issBank.getShortCnName());
			return AjaxResult.successAndData("添加信用卡成功", mer);
		}
		return AjaxResult.error("添加信用卡失败，请联系客服咨询");
	}

	
	/**
	 * 保存或修改账单对象
	 * @param mLimit
	 * @param bankName
	 */
	public void SaveUpdateRemind(MerchantIncreaseLimit mLimit,String bankName){
		Remind r = new Remind();
		r.setId(StringUtils.randomUUID());
		String banknum =mLimit.getBankAccount();
		r.setTitle(bankName+"("+banknum.substring(banknum.length()-4, banknum.length())+")");
		r.setMerchantId(mLimit.getMerchantId());
		r.setRepaymentDay(mLimit.getRepaymentDay());
		r.setBillDay(mLimit.getBillDay());
		r.setType(0);
		r.setIsPayment(0);
		r.setCardId(mLimit.getID());
		List<Remind> li = remindMapper.selctRemindByCardId(mLimit.getID());
		if (li==null || li.size()==0){
			remindMapper.insertRemind(r);
		} else {
			r.setId(li.get(0).getId());
			remindMapper.updateRemind(r);
		}
	}
	
	/**
	 * 修改商户信用卡
	 *
	 * @param merchantIncreaseLimit
	 *            商户信用卡信息
	 * @return 结果
	 */
	@Override
	public int updateMerchantIncreaseLimit(MerchantIncreaseLimit merchantIncreaseLimit) {
		return merchantIncreaseLimitMapper.updateMerchantIncreaseLimit(merchantIncreaseLimit);
	}

	/**
	 * 删除商户信用卡对象
	 *
	 * @param ids
	 *            需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteMerchantIncreaseLimitByIds(String ids) {
		return merchantIncreaseLimitMapper.deleteMerchantIncreaseLimitByIds(Convert.toStrArray(ids));
	}

	/**
	 * 自定义查询商户信用卡详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public MerchantIncreaseLimit selectMerchantDetailById(String id) {
		return merchantIncreaseLimitMapper.selectMerchantDetailById(id);
	}

	/**
	 * app获取信用卡列表
	 */
	@Override
	public AjaxResult selectMerchantIncreaseLimitByMerchantId(String merchantId) {
		if (StringUtils.isEmpty(merchantId)) {
			return AjaxResult.error(1, "获取信用卡信息列表：缺失参数");
		}
		List<CreditCardVo> list = merchantIncreaseLimitMapper.selectCreditCardVoByMerchantId(merchantId);
		if (list != null) {
			for (CreditCardVo cardVo : list) {
				cardVo.setBankBackgroundImg(cardVo.getBankBackgroundImg());
				cardVo.setBankLogoImg(cardVo.getBankLogoImg());
				if (StringUtils.isEmpty(cardVo.getIdCardNumber())) {
					Merchant merchant = merchantMapper.selectMerchantById(merchantId);
					if (merchant != null) {
						cardVo.setIdCardNumber(merchant.getIdCardNumber());
						MerchantIncreaseLimit merchantIncreaseLimit = merchantIncreaseLimitMapper
								.selectMerchantIncreaseLimitById(cardVo.getId());
						merchantIncreaseLimit.setIdCardNumber(merchant.getIdCardNumber());
						merchantIncreaseLimitMapper.updateMerchantIncreaseLimit(merchantIncreaseLimit);
					}
				}
			}
		}
		return AjaxResult.successAndData("获取信用卡列表成功", list);
	}

	/**
	 * 绑定信用卡 获取银行信息
	 *
	 * @param cardId
	 *            信用卡号
	 * @return
	 */
	@Override
	public AjaxResult getCreditCardType(String cardId) {
		Map<String, String> data = new HashedMap<>();
		// 查询卡bin信息
		CardBin cb = binMapper.selectCardBinByBankNo(cardId.length(), cardId);
		// 验证是否属于识别的银行卡
		if (null != cb) {
			// 验证是否贷记卡（信用卡）
			CardType cardType = cardTypeMapper.selectCardTypeByTypeId(cb.getCardTypeId(), 2);
			if (cardType == null) {
				return AjaxResult.error(2, "该银行卡不是信用卡");
			}
			// 获取银行信息
			IssBank issBank = issBankMapper.selectIssBankById(cb.getBankId());
			if (null == issBank) {
				return AjaxResult.error(2, "未获取到所属银行信息");
			}
			// 银行代码
			data.put("bankCode", issBank.getBankCode());
			// 银行名称
			data.put("bankName", issBank.getShortCnName());
			// 银行logo
			data.put("logoImg", issBank.getBankLogoImg());
			return AjaxResult.successAndData("请求成功", data);
		} else {
			return AjaxResult.error("系统检测不到卡Bin信息");
		}
	}

	/**
	 * app 端 获取信用卡信息
	 */
	@Override
	public AjaxResult selectCardVoById(String cardId) {
		if (StringUtils.isEmpty(cardId)) {
			return AjaxResult.error(1, "缺失参数");
		}
		CreditCardVo cardVo = merchantIncreaseLimitMapper.selectCardVoById(cardId);
		if (cardVo == null) {
			return AjaxResult.error(2, "获取卡信息失败");
		}
		cardVo.setBankBackgroundImg(cardVo.getBankBackgroundImg());
		cardVo.setBankLogoImg(cardVo.getBankLogoImg());

		return AjaxResult.successAndData("获取卡信息成功", cardVo);
	}

	/**
	 * 用户解除信用卡绑定
	 *
	 * @param merchantId
	 *            用户id
	 * @param cardId
	 *            信用卡号
	 * @param paymentPwd
	 *            支付密码
	 * @return
	 */
	@Override
	public AjaxResult removeCreditCardByCardIdAndMerchantId(String merchantId, String cardId, String paymentPwd) {
		if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(cardId) || StringUtils.isEmpty(paymentPwd)) {
			return AjaxResult.error(1, "解除信用卡失败：缺失参数");
		}
		Merchant merchant = merchantMapper.selectMerchantById(merchantId);
		if (merchant == null) {
			return AjaxResult.error(2, "该用户不存在");
		}
		if (!StringUtils.equals(merchant.getPaymentPwd(), Md5Utils.encrypt2MD5(paymentPwd))) {
			return AjaxResult.error(3, "输入密码不正确");
		}
		// 查询卡信息>>查询是否启用计划>> 解除绑定信用卡
		MerchantIncreaseLimit increaseLimit = merchantIncreaseLimitMapper.selectCreditCardByCardIdAndMerchantId(cardId,
				merchantId);
		if (increaseLimit == null) {
			return AjaxResult.error(2, "该信用卡不存在");
		}
		// 查询是否遗留计划
		int plan = planNewMapper.selectPlanByCardNumberAndMerchantId(merchantId, cardId);
		if (plan > 0) {
			return AjaxResult.error(4, "解除信用卡失败:该信用卡有任务执行");
		}
		increaseLimit.setSTATUS(IncreaseStatus.D.getCode());
		acqBindMapper.deletByCardId(increaseLimit.getID());
		merchantIncreaseLimitMapper.updateMerchantIncreaseLimit(increaseLimit);
		remindMapper.deleteRemindByCradNumerId(increaseLimit.getID());
		return AjaxResult.success();
	}

	/**
	 * 修改卡信息 ：账单日，还款日 额度
	 *
	 * @param merchantId
	 *            用户id
	 * @param cardId
	 *            信用卡id
	 * @param billDay
	 *            账单日
	 * @param repaymentDay
	 *            还款日
	 * @param limitMoney
	 *            额度
	 * @return
	 */
	@Override
	public AjaxResult updateCreditCard(String merchantId, String cardId, String billDay, String repaymentDay,
			String limitMoney) {
		if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(cardId) || StringUtils.isEmpty(billDay)
				|| StringUtils.isEmpty(repaymentDay) || StringUtils.isEmpty(limitMoney)) {
			return AjaxResult.error(1, "缺失参数");
		}
		MerchantIncreaseLimit increaseLimit = merchantIncreaseLimitMapper.selectCreditCardByCardIdAndMerchantId(cardId,
				merchantId);
		if (increaseLimit == null) {
			return AjaxResult.error(2, "该卡不存在");
		}
		increaseLimit.setBillDay(billDay);
		increaseLimit.setRepaymentDay(repaymentDay);
		increaseLimit.setLimitMoney(limitMoney);
		int r = merchantIncreaseLimitMapper.updateMerchantIncreaseLimit(increaseLimit);
		if (r > 0) {
			return AjaxResult.success();
		}
		return AjaxResult.error();
	}

	@Override
	public MerchantIncreaseLimit selectByBankAccount(String bankCount) {
		return merchantIncreaseLimitMapper.selectByBankAccount(bankCount);
	}

	// 删除卡信息
	@Override
	public AjaxResult deleteIncreaseLimitById(String id) {
		if (StringUtils.isEmpty(id)) {
			return AjaxResult.error(1, "缺失参数");
		}
		MerchantIncreaseLimit increaseLimit = merchantIncreaseLimitMapper.selectMerchantIncreaseLimitById(id);
		if (increaseLimit == null) {
			return AjaxResult.error(1, "获取卡信息失败");
		}

		// 查询是否遗留计划
		int plan = planNewMapper.selectPlanByCardNumberAndMerchantId(increaseLimit.getMerchantId(),
				increaseLimit.getBankAccount());
		if (plan > 0) {
			return AjaxResult.error("删除失败:该信用卡有任务执行");
		}
		increaseLimit.setSTATUS(IncreaseStatus.D.getCode());
		int r1 = merchantIncreaseLimitMapper.updateMerchantIncreaseLimit(increaseLimit);
		acqBindMapper.deletByCardId(id);
		if (r1 > 0) {
			return AjaxResult.success("删除卡信息成功");
		}
		return AjaxResult.error(2, "删除失败");
	}

	/**
	 * app获得银行卡列表(储蓄卡+信用卡)
	 *
	 * @param merchantId
	 * @return
	 */
	@Override
	public AjaxResult selectAllBank(String merchantId) {
		if (StringUtils.isEmpty(merchantId)) {
			return AjaxResult.error(1, "获取信用卡信息列表：缺失参数");
		}
		// 查询用户信息
		Merchant merchant = merchantMapper.selectMerchantById(merchantId);
		// 查询用户信用卡
		List<CreditCardVo> list = merchantIncreaseLimitMapper.selectCreditCardVoByMerchantId(merchantId);
		if (list != null) {
			for (CreditCardVo cardVo : list) {
				cardVo.setBankLogoImg(cardVo.getBankLogoImg());
				cardVo.setBankBackgroundImg(cardVo.getBankBackgroundImg());
				if (StringUtils.isEmpty(cardVo.getIdCardNumber())) {
					if (merchant != null) {
						cardVo.setIdCardNumber(merchant.getIdCardNumber());
						MerchantIncreaseLimit merchantIncreaseLimit = merchantIncreaseLimitMapper
								.selectMerchantIncreaseLimitById(cardVo.getId());
						merchantIncreaseLimit.setIdCardNumber(merchant.getIdCardNumber());
						merchantIncreaseLimitMapper.updateMerchantIncreaseLimit(merchantIncreaseLimit);
					}
				}
			}
		}
		// 储蓄卡
		MyBankAllVO myBankAllVO = new MyBankAllVO();
		// 储蓄卡号
		myBankAllVO.setBankAccount(merchant.getBankAccount());
		// 持卡人手机号
		myBankAllVO.setBankPhone(merchant.getReservePhone());
		// 储蓄卡名称
		myBankAllVO.setBankName(merchant.getBankName());
		// 持卡人名称
		myBankAllVO.setBankAccountName(merchant.getMerchantCnName());
		// 根据银行代号查询
		IssBank issBank = issBankMapper.selectIssBankByCode(merchant.getBankCode());
		// 银行卡图片
		if (!StringUtils.isEmpty(issBank.getDepositCardImg())) {
			myBankAllVO.setBankBackgroundImg(issBank.getDepositCardImg());
		} else {
			myBankAllVO.setBankBackgroundImg("");
		}
		Map<String, Object> map = new HashMap<>(16);
		map.put("bankCard", myBankAllVO);
		map.put("list", list);
		return AjaxResult.successAndData("获取信用卡列表成功", map);
	}

	/**
	 * 信用卡签约状态查询
	 *
	 * @param companyId
	 *            公司id
	 * @param acqMerchantNo
	 *            上游商户号
	 * @param bankAccount
	 *            卡号
	 * @param trxSourceIp
	 *            终端ip
	 * @return
	 */
	@Override
	public AjaxResult getBankCardSignQuery(String companyId, String acqMerchantNo, String bankAccount,
			String trxSourceIp) {
		MerchantIncreaseLimit mer = new MerchantIncreaseLimit();
		// 流水号
		mer.setSeriaNo(StringUtils.createNum());
		// 公司编号
		mer.setCompanyId(companyId);
		// 用户编号
		mer.setUserId(acqMerchantNo);
		// 卡号
		mer.setBankAccount(bankAccount);
		// 调用段ip地址
		mer.setTrxSourceIp(trxSourceIp);
		JSONObject gg = null;
		try {
			// 上送 信用卡签约状态查询信息
			gg = GuangGuUtil.bankCardSignQuery(mer);
			if (StringUtils.isNotNull(gg)) {
				String retCode = gg.getString("ret_code");
				String resCode = gg.getString("res_code");
				if (("SUCCESS").equals(retCode)) {
					if (("YQB000000").equals(resCode)) {
						/** 签约状态 0 待开通 1 等待签约中 2 开通成功 3 开通失败 4 绑卡状态失效 */
						String signStatus = gg.getString("status");
						if ((SignStatus.OK.getCode()).equals(signStatus)) {
							return AjaxResult.success(SignStatus.OK.getInfo());
						} else {
							return AjaxResult.success(SignStatus.WANT.getInfo());
						}
					} else {
						return AjaxResult.success(gg.getString("res_msg"));
					}
				}
			}
		} catch (Exception e) {
			log.error("信用卡签约上送异常", e);
			return AjaxResult.error("发送失败,如有疑问请咨询客服原因");
		}
		return AjaxResult.error("查询失败");
	}

	/**
	 * 验证是否开通过通道
	 *
	 * @param cardId
	 *            卡ID
	 * @return
	 */
	@Override
	public AjaxResult getcardBind(String cardId) {
		List<AcqBind> al = acqBindMapper.selectByCardId(cardId);
		List<String> li = new ArrayList<String>();
		if (al.size() > 0) {
			for (AcqBind a : al) {
				li.add(a.getAcqId());
			}
			return AjaxResult.successAndData("已开通通道", al);
		} else {
			return AjaxResult.errorAndData("您本张信用卡，还未开通任何通道。请先开通！", li);
		}
	}

	/********************************** 辅助方法 ***********************************/

	public MerchantIncreaseLimit merchantIncreaseLimit(String acqMerchantNo, String companyId, String bankAccountName,
			String bankAccount, String idCardNumber, String bankPhone, String cvn, String expDate, String trxSourceIp,
			String smsCode) {
		MerchantIncreaseLimit mer = new MerchantIncreaseLimit();
		// 公司编号
		mer.setCompanyId(companyId);
		// 用户编号
		mer.setUserId(acqMerchantNo);
		// 姓名/银行卡账户名
		mer.setBankAccountName(bankAccountName);
		// 信用卡号
		mer.setBankAccount(bankAccount);
		// 身份证号码
		mer.setIdCardNumber(idCardNumber);
		// 预留的手机号
		mer.setBankPhone(bankPhone);
		if (StringUtils.isNotEmpty(cvn)) {
			// 信用卡背后三位
			mer.setCvn(cvn);
		}
		if (StringUtils.isNotEmpty(expDate)) {
			// 有效期
			mer.setExpdate(expDate);
		}
		if (StringUtils.isNotEmpty(smsCode)) {
			// 短信验证吗
			mer.setSmsCode(smsCode);
		}
		if (StringUtils.isNotEmpty(trxSourceIp)) {
			// 终端ip
			mer.setTrxSourceIp(trxSourceIp);
		}
		return mer;
	}

	public MerchantIncreaseLimit bindCardMsgLimit(String acqMerchantNo, String companyId, String bankAccountName,
			String bankAccount, String idCardNumber, String bankPhone, String cvn, String expdate, String trxSourceIp) {
		MerchantIncreaseLimit mer = new MerchantIncreaseLimit();
		// 公司编号
		mer.setCompanyId(companyId);
		// 用户编号
		mer.setUserId(acqMerchantNo);
		// 姓名/银行卡账户名
		mer.setBankAccountName(bankAccountName);
		// 信用卡号
		mer.setBankAccount(bankAccount);
		// 身份证号码
		mer.setIdCardNumber(idCardNumber);
		// 预留的手机号
		mer.setBankPhone(bankPhone);
		if (StringUtils.isNotEmpty(cvn)) {
			// CVN信用卡背后三位
			mer.setCvn(cvn);
		}
		if (StringUtils.isNotEmpty(expdate)) {
			// 有效期
			mer.setExpdate(expdate);
		}
		if (StringUtils.isNotEmpty(trxSourceIp)) {
			// 终端ip
			mer.setTrxSourceIp(trxSourceIp);
		}
		return mer;
	}

	/**
	 * DES敏感信息脱敏
	 *
	 * @return
	 */
	private MerchantIncreaseLimit deDensity(MerchantIncreaseLimit mer) {
		if (mer != null) {
			// 身份证号
			mer.setBankAccount(EncryptUtil.desEncryptMessage(mer.getBankAccount()));
			// 银行卡号
			mer.setIdCardNumber(EncryptUtil.desEncryptMessage(mer.getIdCardNumber()));

		}
		return mer;
	}

	@Override
	public long selectCountByMerchantId(String merchantId) {
		// TODO Auto-generated method stub
		return merchantIncreaseLimitMapper.selectCountByMerchantId(merchantId);
	}
}
